﻿using System;
using System.Text.RegularExpressions;
using System.Net;

namespace Kwan.Helper.Strings
{
    public static class Format
    {
        #region CutString 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="fileName">起始字符串</param>
        /// <param name="fileName">结束字符串</param>
        /// <returns>提示信息</returns>
        public static string[] CutString(string str, string begin, string end)
        {
            Regex reg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            string[] str_ = new string[reg.Matches(str).Count];
            int i = 0;
            foreach (Match match in reg.Matches(str))
            {
                str_.SetValue(match.Value, i);
            }
            return str_;
        }
        #endregion

        #region GetImgUrl 获取HTML中所有图片的 URL。
        /// <summary>
        /// 获取HTML中所有图片的 URL。
        /// </summary>
        /// <param name="sHtmlText">HTML代码</param>
        /// <returns>图片的URL列表</returns>
        public static string[] GetImgUrl(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);

            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;

            return sUrlList;
        }
        #endregion

        #region RemoveHtml 去除HTML标记
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string RemoveHtml(string strHtml)
        {
            Regex objRegExp = new Regex("<(.|\n)+?>");
            string strOutput = objRegExp.Replace(strHtml, "");
            strOutput = strOutput.Replace("<", "");
            strOutput = strOutput.Replace(">", "");
            return strOutput.Trim();
        }
        #endregion

        #region RemoveHtmlSP 去除HTML标记（<P>、<IMG>、<BR>除外）
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string RemoveHtmlSP(string strHtml)
        {
            if (strHtml == null) return strHtml;
            Regex objRegExp = new Regex(@"(?i)<(?!p|br|img).*?>", RegexOptions.IgnoreCase);
            return objRegExp.Replace(strHtml, "");
            //return regex.Replace(strHtml, "").Replace("&nbsp;", "").Replace("\n", "").Replace("\r", "");
        }
        #endregion

        #region ReplaceRemoteUrl 替换下载远程图片及入库操作
        /// <summary>
        /// ReplaceRemoteUrl 替换下载远程图片及入库操作
        /// </summary>
        /// <param name="strInput">内容</param>
        /// <returns>返回string类型;替换后的内容</returns>
        public static string ReplaceRemoteUrl(string strInput,string serverPath)
        {
            string tempFilePath = "";
            string outStr;
            outStr = strInput;

            //获取远程图片url集合
            string _pattern = @"(http|https|ftp|rtsp|mms):(\/\/|\\\\){1}((([\w-])+[.]){1,}(net|com|cn|org|cc|tv|[0-9]{1,3}))([^\?\s]*\/)(([^\?\s])+[.]{1}(gif|jpg|png|bmp))";
            MatchCollection found = null;
            RegexOptions TheOptions;
            TheOptions = RegexOptions.Singleline | RegexOptions.IgnoreCase;
            Regex r = new Regex(_pattern, TheOptions);
            found = r.Matches(strInput);
            foreach (Match m in found)
            {
                tempFilePath = "";
                if (m.Value.Length > 0)
                {
                    tempFilePath = DownloadImage(m.Value, serverPath);
                    //如果下载成功
                    if (tempFilePath.Length > 0)
                    {
                        outStr = outStr.Replace(m.Value, "/Upload/News/pNews/" + tempFilePath);
                    }
                }
            }

            return outStr;
        }
        #endregion

        #region DownloadImage 下载远程图片
        /// <summary>
        /// 下载远程图片
        /// </summary>
        /// <param name="strUrl">将要下载的图片地址</param>
        /// <returns>返回string类型;图片的本地地址</returns>
        private static string DownloadImage(string strUrl, string serverPath)
        {
            try
            {
                string fileExt = System.IO.Path.GetExtension(strUrl);
                string fileName = Guid.NewGuid().ToString("N");
                string filePath = fileName + fileExt;
                string tempFolder = System.IO.Path.GetDirectoryName(serverPath + filePath);
                if (!System.IO.Directory.Exists(tempFolder))
                {
                    System.IO.Directory.CreateDirectory(tempFolder);
                }
                WebClient wc = new WebClient();
                wc.DownloadFile(strUrl, serverPath + filePath);
                wc.Dispose();
                return filePath;
            }
            catch
            {
                return string.Empty;
            }
        }
        #endregion
    }
}
